<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="getTitle"
    @ok="handleSubmit"
  >
    <BasicForm
      @register="registerForm"
      @submit="handleSubmit"
      @reset="handleReset"
    />
  </BasicModal>
</template>

<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicModal, useModalInner } from '@/components/Modal';
import { BasicForm, FormSchema, useForm } from '@/components/Form';
import { create${entity}, update${entity} } from '@/api/${table.entityPath}Api';
import type { ${entity}Info } from '@/api/${table.entityPath}Api';
import { useMessage } from 'naive-ui';

const emit = defineEmits(['reload', 'register']);
const message = useMessage();

const isUpdate = ref(false);
const rowId = ref('');

const schemas: FormSchema[] = [
<#list table.fields as field>
  {
    field: '${field.propertyName}',
    label: '${field.comment}',
    component: 'NInput',
    required: ${field.propertyRequired?string('true', 'false')},
  },
</#list>
];

const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
  labelWidth: 100,
  schemas,
  showActionButtonGroup: false,
});

const [register, { setModalProps, closeModal }] = useModalInner(async (data) => {
  resetFields();
  setModalProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;

  if (unref(isUpdate)) {
    rowId.value = data.record.id;
    setFieldsValue({
      ...data.record,
    });
  }
});

const getTitle = computed(() => (!unref(isUpdate) ? '新增${table.comment!}' : '编辑${table.comment!}'));

async function handleSubmit() {
  try {
    const values = await validate();
    setModalProps({ confirmLoading: true });
    
    if (!unref(isUpdate)) {
      await create${entity}(values);
    } else {
      await update${entity}({ ...values, id: rowId.value });
    }

    closeModal();
    emit('reload');
    message.success('操作成功');
  } catch (error) {
    message.error('操作失败');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}

function handleReset() {
  resetFields();
}
</script> 